import sys
import random
import pygame

def run():

    Block_size = 24
    coords = []
    for i in range(5, 580+1, 24+5):
        coords.append(i)
    fps = 2
    screen = pygame.display.set_mode((480+100, 480+100))
    pygame.display.set_caption('ZMEYA')
    rows = (480-24*2) // 24
    colomns = (480-24*2) // 24
    margin = 5
    score = 0
    apple_c = 0
    lives = 2
    with open('record.txt', 'r') as f:
        record = int(f.readline())

    pygame.font.init()
    font_record = pygame.font.SysFont('Arial', 20)
    font_score = pygame.font.SysFont('Arial', 20)
    font_over = pygame.font.SysFont('Arial', 40)

    def draw_block(row, colomn, color):
        margin = 5
        pygame.draw.rect(screen, color, [Block_size + colomn * Block_size + margin * (colomn + 1),
                                         margin + Block_size + row * Block_size + margin * (row + 1),
                                         Block_size, Block_size])

    def draw_squares(rows, colomns, margin):
        for i in range(rows):
            for e in range(colomns):
                if (e+i) % 2 != 0:
                    color = 'white'
                else:
                    color = 'green'
                pygame.draw.rect(screen, color, [Block_size + e * Block_size + margin * (e + 1),
                                               margin + Block_size + i * Block_size + margin * (i + 1),
                                               Block_size, Block_size])

    class Snake():

        def __init__(self, x, y):
            self.x = x
            self.y = y

        def check(self):
            return 0 <= self.x < 18 and 0 <= self.y < 18

    class Apple():

        def __init__(self,x,y):
            self.x = x
            self.y = y

    apple = Apple(random.randint(0, 17), random.randint(0, 17))
    d_row = 0
    d_col = 1
    snake = [Snake(9, 7), Snake(9, 8), Snake(9, 9)]
    snake_restart = [Snake(9, 7), Snake(9, 8), Snake(9, 9)]
    timer = pygame.time.Clock()

    while True:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                with open('record.txt', 'w') as f:
                    f.write(str(record))
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and d_col != 0:
                    d_row = -1
                    d_col = 0
                elif event.key == pygame.K_DOWN and d_col != 0:
                    d_row = 1
                    d_col = 0
                elif event.key == pygame.K_LEFT and d_row != 0:
                    d_row = 0
                    d_col = -1
                elif event.key == pygame.K_RIGHT and d_row != 0:
                    d_row = 0
                    d_col = 1

        screen.fill('cyan')

        draw_squares(rows=rows, colomns=colomns, margin=margin)

        if score == apple_c:
            apple.x = random.randint(0, 17)
            apple.y = random.randint(0, 17)
            apple_c += 1
        draw_block(apple.x, apple.y, 'red')
        head = snake[-1]

        if not head.check():
            fps = 0
        for i in snake:
            draw_block(i.x, i.y, (62, 0, 95))
        if head.x == apple.x and head.y == apple.y:
            fps += 0.5
            score += 1
            snake.append(Snake(apple.x, apple.y))

        new_head = Snake(head.x + d_row, head.y + d_col)
        snake.append(new_head)
        snake.pop(0)

        for i in snake:
            if d_col == 0:
                i.y += d_col
            if d_row == 0:
                i.x += d_row
        for i in range(len(snake)-1):
            if new_head.x == snake[i].x and new_head.y == snake[i].y:
                print('GAME OVER')
                fps = 0
                break

        with open('record.txt', 'w') as f:
            if score > record:
                record = score
                f.write(str(record))

        if fps == 0:
            screen.blit(font_over.render("GAME OVER",True,'red'),(580//2-124,580//2-100))
            screen.blit(font_score.render("Press SPACE to restart", True, 'black'), (290-100,235))
            if fps != 2:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        with open('record.txt', 'w') as f:
                            f.write(str(record))
                        sys.exit()
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_SPACE:
                            score = 0
                            fps = 2
                            snake = snake_restart
                            d_row = 0
                            d_col = 1

        screen.blit(font_score.render(f"Score: {score}", True, "black"), (10, 10))
        screen.blit(font_score.render(f"Record: {record}", True, "black"), (240, 10))
        screen.blit(font_score.render(f"Speed: {fps}", True, "black"), (480, 10))

        pygame.display.flip()

        timer.tick(fps)

run()